package com.pxxy.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.pxxy.mall.product.dao.CategoryBrandRelationDao;
import com.pxxy.mall.product.entity.CategoryBrandRelationEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxxy.common.utils.PageUtils;
import com.pxxy.common.utils.Query;

import com.pxxy.mall.product.dao.BrandDao;
import com.pxxy.mall.product.entity.BrandEntity;
import com.pxxy.mall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BrandEntity> page;
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    new QueryWrapper<BrandEntity>().lambda().eq(BrandEntity::getBrandId, key).or().eq(BrandEntity::getName, key)
            );
        } else {
            page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    new QueryWrapper<BrandEntity>());
        }
        return new PageUtils(page);
    }

    /**
     * 修改品牌名的同时品牌分类关系表中的名字也要修改
     * @param entity
     * @return
     */
    @Transactional
    @Override
    public void updateDetail(BrandEntity entity) {
        if (!StringUtils.isEmpty(entity.getName())) {
            BrandEntity brandEntity = this.lambdaQuery().eq(BrandEntity::getBrandId, entity.getBrandId()).one();
            categoryBrandRelationDao.update(getCategoryBrandRelation(entity),
                    new UpdateWrapper<CategoryBrandRelationEntity>()
                            .lambda()
                            .eq(CategoryBrandRelationEntity::getBrandId, entity.getBrandId()));
            this.updateById(entity);
        }
    }



    private CategoryBrandRelationEntity getCategoryBrandRelation(BrandEntity entity) {
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setBrandId(entity.getBrandId());
        categoryBrandRelationEntity.setBrandName(entity.getName());
        return categoryBrandRelationEntity;
    }
}